from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

MODEL_KWARGS = {
    "blank": True,
    "null": True,
}

CMODEL_KWARGS = {
    "max_length": 125,
    "blank": True,
    "null": True,
}

FMODEL_KWARGS = {
    "blank": True,
    "null": True,
    "on_delete": models.SET_NULL,
    "db_constraint": False
}

MMODEL_KWARGS = {
    "blank": True,
    "db_constraint": False
}


class IsDeletedManager(models.Manager):

    def all(self):
        return super().all().filter(is_deleted=False)

    def filter(self, *args, **kwargs):
        if kwargs.get('is_deleted') is None:
            kwargs['is_deleted'] = False

        return super().filter(*args, **kwargs)


class TimeBaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, **MODEL_KWARGS)
    updated_at = models.DateTimeField(auto_now=True, **MODEL_KWARGS)

    class Meta:
        abstract = True


class UidBaseModel(models.Model):
    uid = models.CharField(unique=True, **CMODEL_KWARGS)
    name = models.CharField(**CMODEL_KWARGS)

    class Meta:
        abstract = True


class IsDeletedBaseModel(models.Model):
    is_deleted = models.BooleanField(
        default=False,
        **MODEL_KWARGS
    )
    objects = IsDeletedManager()

    class Meta:
        abstract = True


class TreeModel(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
    order_num = models.IntegerField(default=0, verbose_name='排序字眼', **MODEL_KWARGS)

    class MPTTMeta:
        order_insertion_by = ['order_num']

    class Meta:
        abstract = True
